package com.ftf.tp.blog.domain.article.service;


import com.alibaba.fastjson.JSONObject;
import com.ftf.tp.blog.domain.article.aggregate.ArticleAgg;
import com.ftf.tp.blog.domain.article.dos.SupportDO;
import com.ftf.tp.blog.domain.article.repository.ArticleRepository;
import com.ftf.tp.common.constants.RedisConstant;
import com.ftf.tp.common.core.redis.utils.RedissonHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 文章service
 *
 * @author tanghao
 * @date 2021/10/18
 */
@Slf4j
@Service
public class ArticleService {

    @Resource
    private RedissonHelper redissonHelper;

    @Resource
    private ArticleRepository articleRepository;

    /**
     * 文章数据user_background
     *
     * @param articleAgg 文章聚合
     */
    public void initialSave(ArticleAgg articleAgg) {
        articleRepository.initialSave(articleAgg);
        //将初始热度值缓存
        redissonHelper.addZset(RedisConstant.REDIS_KEY_BLOG_HOT_VALUE,
                articleAgg.getId(), Double.valueOf(articleAgg.getArticleDataDO().getHotValue()));
    }

    /**
     * 文章点赞
     *
     * @param supportDO 参数
     */
    public void articleSupport(SupportDO supportDO) {
        String sumKey = RedisConstant.REDIS_KEY_ARTICLE_SUPPORT_SUM + supportDO.getTargetId();
        String supportRecordKey = RedisConstant.REDIS_KEY_ARTICLE_SUPPORT + supportDO.getTargetId();
        Boolean isSupport = articleRepository.isSupport(supportDO.getUserId(), supportDO.getTargetId());
        if (supportDO.getSupportType().equals(0) && !isSupport) {
            try {
                //数据库记录点赞
                articleRepository.support(supportDO);
            } catch (Exception e) {
                log.error("系统异常 重复点赞 {}", JSONObject.toJSONString(sumKey), e);
                return;
            }
            //缓存记录点赞数
            articleRepository.articleSupportSum(sumKey, supportDO.getTargetId());

            //缓存记录点赞记录
            redissonHelper.addZset(supportRecordKey, supportDO.getUserId(), (double) supportDO.getSupportTime().getTime());
        } else if (supportDO.getSupportType().equals(1) && isSupport) {
            articleRepository.cancelSupport(supportDO.getUserId(), supportDO.getTargetId());
            if (redissonHelper.removeZset(supportRecordKey, supportDO.getUserId())) {
                articleRepository.articleSupportSum(sumKey, supportDO.getTargetId());
            }
        } else {
            log.warn("点赞消息有误,重复行为 {}", JSONObject.toJSONString(supportDO));
        }
    }


}
